from sqlalchemy.orm import Session
from sqlalchemy import Table, MetaData
from ..models.user import User
from ..data_clean.models import DataCleanTask
from .database import SessionLocal, engine, Base
from passlib.context import CryptContext
from datetime import datetime

# 创建密码上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)

def init_db():
    """初始化数据库"""
    try:
        # 创建元数据对象
        metadata = MetaData()
        
        # 定义用户表
        users = Table(
            'users', metadata,
            *[c.copy() for c in User.__table__.columns]
        )
        
        # 定义数据清洗任务表
        data_clean_tasks = Table(
            'data_clean_tasks', metadata,
            *[c.copy() for c in DataCleanTask.__table__.columns]
        )
        
        # 创建表
        metadata.create_all(engine)
        print("数据库表创建完成")
        
        # 获取数据库会话
        db = SessionLocal()
        
        try:
            # 检查是否已存在管理员用户
            admin = db.query(User).filter(User.username == "admin").first()
            if not admin:
                # 创建管理员用户
                admin_user = User(
                    username="admin",
                    email="admin@example.com",
                    hashed_password=get_password_hash("admin123"),
                    is_active=True,
                    is_superuser=True,
                    created_at=datetime.now(),
                    last_login=datetime.now()
                )
                db.add(admin_user)
                db.commit()
                print("已创建管理员用户")
            else:
                print("管理员用户已存在")
            
            print("数据库初始化完成")
        
        except Exception as e:
            print(f"初始化数据库时出错: {str(e)}")
            db.rollback()
            raise
        finally:
            db.close()
    
    except Exception as e:
        print(f"创建数据库表时出错: {str(e)}")
        raise

if __name__ == "__main__":
    init_db() 